/*
 * @Author: gk 
 *  文件资源
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: gk
 * @Last Modified time: 2018-05-09 14:31:14
 */
layui.config({
}).use(['element', 'table', 'tree', 'treeGrid', 'zlSelectEx', 'zlPopSourceForm', 'zlPinYin', 'upload', 'dropdown', 'zlPrint'], function (exports) {
	var $ = layui.$
		, zlContext = layui.zlContext
		, layer = layui.layer
		, form = layui.form
		, element = layui.element
		, treeGrid = layui.treeGrid
		, zlPinYin = layui.zlPinYin
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, ERROR = zlConfig.global.result.errorState
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-80';
	$(window).on('resize', function () {
		$('.docking-left').height($(window).height() - 10);
		$('.docking-fill').height($(window).height() - 10);
	}).resize();

	var fromlayerIndex;

	//渲染报表列表
	treeGrid.render({
		elem: '#tbReport'
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, limit: 10000
		, treeId: 'QINGCZB_ID'//树形id字段名称
		, treeUpId: 'SYS_PARENTID'//树形父id字段名称
		, treeShowName: 'QINGCZB_QINGCJZR'//以树形式显示的字
		, cols: [[ //表头
			{ type: 'checkbox', fixed: 'left' }
			, { field: 'QINGCZB_QINGCJZR', width: '175', title: '清查基准日' }
			, { field: 'QINGCZB_BAOSRQ', width: '100', title: '报送日期' }
			, { field: 'QINGCZB_YOUZBM', width: '100', title: '邮政编码' }
			, { field: 'QINGCZB_DIANHHM', width: '100', title: '机构地址' }
			, { field: 'QINGCZB_TIANBR', width: '100', title: '填表人' }
			, { field: 'QINGCZB_CAIWFZR', width: '100', title: '财务负责人' }
			, { field: 'QINGCZB_DANWFZR', width: '100', title: '机构负责人' }
			, { field: 'QINGCZB_DANWMC', width: '100', title: '机构名称' }
			, {
				field: 'SYS_AUDFLAG', title: '审核', width: 60, templet: function (d) {
					return '<input type="checkbox" name="SYS_AUDFLAG" value="' + d.SYS_AUDFLAG + '" disabled lay-skin="primary" ' + (d.SYS_AUDFLAG ? "checked" : "") + '>'
				}
			}
			, { fixed: 'right', field: 'OPTION', width: 250, title: '操作', align: 'center', toolbar: '#barReport' }
		]]
		, event:
		{
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
		, page: false
	});
	var treeTable = {
		getSelectedNodes: function () {
			var checkStatus = treeGrid.checkStatus('tbReport');
			return checkStatus.data;
		}
	}
	var gridAction = {
		currentEditObj: undefined,
		gridEdit: function (parentrow, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'	<div class="layui-form-item layui-hide" id="divcotnext">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="SYS_PARENTID" class="layui-input">'
				, '			<input type="text" name="QINGCZB_ID" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, ' <div class="layui-tab layui-tab-brief" lay-filter="test">'
				, ' 	<ul class="layui-tab-title">'
				, '			<li class="layui-this">清查明细</li>'
				, '			<li>清查报表</li>'
				, ' 	</ul> '
				, '		<div class="layui-tab-content">'
				, '			<div class="layui-tab-item layui-show">'
				, '				<iframe id="framx" scrolling="no" frameborder="0" style="overflow: auto; margin: auto; width: 100%;" src="/kdayun-report-fr/ReportServer?reportlet=[6e05][67e5][62a5][8868]\\[8d44][4ea7][6e05][67e5][660e][7ec6][8868].cpt&op=write"></iframe>'
				, '			</div>'
				, '			<div class="layui-tab-item">'
				, ' 			<iframe id="frahz" scrolling="no" frameborder="0" style="overflow: auto; margin: auto; width: 100%;" src="/kdayun-report/reportJsp/previewInput.jsp?rpxHome=../kdayun/WEB-INF/static/appdata/filesres/reports&sht=DB11198BA6694DD8BA37E42A84C21762.sht&dfxHome="></iframe>'
				, ' 		</div>'
				, '		</div>'
				, '	</div>'
			];

			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '[XXXXX]清查报表'),
				id: 'qingchaLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					var ssheight = $("#divcotnext").parent().height() - 50;
					$("#framx").height(ssheight);
					$("#frahz").height(ssheight);
					element.on('tab(test)', function (elem) {
						element.tabChange('test', elem);
					});

					if (type == 'edit') {
						zlContext.autoFill($('#frmEditGrid'), row);
						$('#frmEditGrid input[name=EDITTYPE]').val('edit');
						form.render();
					}
					else {
						/**设置隐藏属性*/
						$('#frmEditGrid input[name=EDITTYPE]').val('new');
						if (parentrow) {
							$('#frmEditGrid input[name=SYS_PARENTID]').val(parentrow['QINGCZB_ID']);
						}
						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmEditGrid input[name=REP_MINGC]').change(function () {
							var v = $('#frmEditGrid input[name=REP_MINGC]').val();
							/**设置报表名 */
							var v1 = zlPinYin.C(v);
							$('#frmEditGrid input[name=REP_BIANH]').val(v1);
							form.render();
						});
					}
					fromlayerIndex = index;
				}
			});
		},
		viewRow: function (row) {
			gridAction.gridEdit(null, row, 'edit', true);
		},
		newRow: function () {
			zlContext.confirm('询问', '提数会覆盖原来的清查报表数据？</br> 按【确定】继续提数 </br> 按【取消】取消提数', function (index) {
				var nodes = treeTable.getSelectedNodes();
				gridAction.gridEdit(nodes.length > 0 ? nodes[0] : null, null, 'new');
				layer.close(index);
			});
		},
		editRow: function (row) {
			gridAction.gridEdit(null, row, 'edit');
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的报表');
				return;
			}
			for (var i = 0; i < rows.length; i++) {
				if (rows[i].children.length > 0) {
					zlContext.warnMsg(rows[i].REP_MINGC + "功能节点下还有子功能，请先删除子功能");
					canpost = false;
					return;
				}
			}
			zlContext.confirm('询问', '是否要删除选择的报表?', function (index) {
				// var param = { id: rows[0]['QINGCZB_ID'] };
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/report/qingchs/remove', { id: rows[0]['QINGCZB_ID'] }, function (result) {
					if (result[statusName] == OK) {
						gridAction.currentEditObj.del();
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		export: function (row) {
			if ($("#ifexport").length == 0) {
				$("body").append('<iframe id=ifexport style="display:none"></iframe>');
			}
			$("#ifexport").attr("src", layui.cache['contentPath'] + row['REP_WENJLJ']);
			iframe = $("#ifexport")[0];
			iframe.onload = iframe.onreadystatechange = function iframeload() {
				if (!iframe.readyState || iframe.readyState == "complete") {
					//alert("Local iframe is now loaded.");
				}
			};
		},
		sumbit: function (fields) {
			var editType = $('#frmEditGrid input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/report/qingchs/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/report/qingchs/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refresh: function (node) {
			$('#edtSeacherValue').val("")
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			}
			else if (type == 'new') {
				treeGrid.reload('tbReport');
			}
		},
		getParams: function () {
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			var chkRows = treeTable.getSelectedNodes();
			var chkrwids = [];
			$.each(chkRows, function (index, row) {
				chkrwids.push(row.QINGCZB_ID);
			});
			param['chkrwids'] = chkrwids.join(',');
			return param;
		}
	}
	$('#btnReportRefresh').on('click', function () {
		gridAction.refresh(null);
	});
	$('#btnReportNew').on('click', function () {
		gridAction.newRow();
	});
	$('#btnReportDelete').on('click', function () {
		var rows = treeTable.getSelectedNodes();
		gridAction.deleteRows(rows);
	});
	$('#btnSeacher').on('click', function () {
		gridAction.search();
	});
	$('#edtSeacherValue').on('keypress', function (event) {
		if (event.keyCode == 13) {
			gridAction.search();
		}
	});
	treeGrid.on('tool(tbReport)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		var tr = obj.tr; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		} else if (layEvent == 'export') {
			gridAction.export(row);
		} else if (layEvent == 'import') {
			gridAction.currentEditObj = obj;
		}
	});
	//提交
	form.on('submit(frmEditGrid)', function (frm) {
		return gridAction.sumbit(frm.field);
	});
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
		var loadGridData = function (tableId, url, param) {
			treeGrid.reload(tableId, {
				url: url
				, height: fullheight
				, page: false
				, limit: 10000
				, method: 'post'
				, where: param
				, done: function (res, curr, count) {
					layer.close(index);
				}
			});
		}
		//刷新
		loadGridData('tbReport', layui.cache['contentPath'] + '/report/qingchs/query', param);
	});

	gridAction.refresh(null);
});